/*
 * filemanager.cpp
 *
 *  Created on: Nov 23, 2009
 *      Author: Wim
 */

#include "filemanager.h"
#include <iostream>
using std::cout;
using std::endl;
#include <sstream>
using std::ostringstream;

#include <vector>
using std::vector;

#include <Poco/FileStream.h>
using Poco::FileInputStream;
using Poco::FileOutputStream;

#include <Poco/Hash.h>

#include <Poco/StreamCopier.h>
using Poco::StreamCopier;

#include <Poco/Path.h>
using Poco::Path;

FileManager::FileManager(string filedir) :
	_filedir( (filedir == "" ? Path::current() : Path(filedir).makeDirectory() ))
{
	cout << "FileManager :: Created with working directory '" << _filedir.path() << "'" << endl;
}

FileManager::~FileManager()
{}


void FileManager::addFile(string filename, File file)
{
	File nfile(Path(_filedir.path(),filename));
	File ofile(Path(file.path()).absolute());
	cout << "FileManager :: about to add a file" << endl;
	cout << "FileManager :: Manual check :: nfile :: " << nfile.path() << endl;
	cout << "FileManager :: Manual check :: ofile :: " << ofile.path() << endl;
	if ( nfile != ofile )
	{
		cout << "FileManager :: adding \"" << nfile.path() << "\" from \"" << ofile.path() << "\"" << endl;
		FileOutputStream fout(nfile.path());
		FileInputStream fin(ofile.path());
		StreamCopier::copyStream(fin,fout);
	}
}

File FileManager::searchFile(string filename)
{
	File f(Path(_filedir.path(), filename));
	if (!f.exists())
		throw FileNotFoundException();
	return f;
}

void FileManager::removeFile(string filename)
{
	cout << "FileManager :: Going to try to remove '" << filename << "'" << endl;
	try
	{
		File f = searchFile(filename);
		f.remove();
		cout << "FileManager :: Removed '" << f.path() << "'" << endl;
	} catch (FileNotFoundException e) {
		cout << "FileManager :: The file '" << filename << "' was not found and could not be removed." << endl;
	}
}


UInt32 FileManager::hash(File file)
{
	Path p(file.path());
	return FileManager::hash(p.getFileName());
}

UInt32 FileManager::hash(string filename)
{
	Path p(filename);
	return UInt32(Poco::hash(p.getFileName()));
}

vector<File> FileManager::getFiles()
{
	vector<File> everything;
	vector<File> files;

	_filedir.list(everything);

	for (vector<File>::iterator it = everything.begin(); it != everything.end(); ++it)
		if (it->isFile())
			files.push_back(*it);

	return files;
}
